import React, { PropsWithChildren } from 'react';
import { Provider } from 'react-redux';

import { ModalContext } from '@/shared/context/ModalContext';
import { useModal } from '@/shared/lib/hooks';
import type { AppProps } from 'next/app';
import { SnackbarProvider } from 'notistack';

import { usePreserveScroll } from '../lib';
import { wrapper } from '../model';
import { AuthProvider } from './auth.provider';
import { AuthProtector } from './AuthProtector';
import { ModalContainer } from './ModalContainer';
import { PrevRouterProvider } from './prevRouter.provider';

export const RootProvider = ({ children, ...pageProps }: Omit<AppProps, 'Component'> & PropsWithChildren) => {
  const { store } = wrapper.useWrappedStore(pageProps);
  const [init, setInit] = React.useState<boolean>(false);
  const [data, setData] = React.useState<any>(null);
  const { openModal, closeModal, id } = useModal();
  React.useEffect(() => {
    setInit(true);
  }, []);
  usePreserveScroll();
  return (
    // <ErrorBoundary>
    <Provider store={store}>
      <SnackbarProvider
        anchorOrigin={{
          vertical: 'top',
          horizontal: 'center',
        }}
        autoHideDuration={2000}
        maxSnack={1}
        preventDuplicate
      >
        <PrevRouterProvider>
          <ModalContext.Provider value={{ closeModal, openModal, id, data, setData }}>
            {init && (
              <AuthProvider>
                <AuthProtector>{children}</AuthProtector>
              </AuthProvider>
            )}
            <ModalContainer />
          </ModalContext.Provider>
        </PrevRouterProvider>
      </SnackbarProvider>
    </Provider>
    // </ErrorBoundary>
  );
};
